package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.sun.xml.bind.v2.schemagen.xmlschema.TypeHost;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * deviceService业务层处理
 *
 * @author lzl
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询device
     *
     * @param id device主键
     * @return device
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询device列表
     *
     * @param device device
     * @return device
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增device
     *
     * @param device device
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }


    /**
     * 批量删除device
     *
     * @param ids 需要删除的device主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new RuntimeException("同步产品列表失败");
        }
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        String allProductList = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(allProductList)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(allProductList, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        //1.判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0) {
            throw new RuntimeException("设备名称已存在");
        }
        //2.判断设备标识是否重复
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0) {
            throw new RuntimeException("设备标识已存在");
        }
        //3.判断同一位置是否绑定相同的设备
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );
        if (count > 0) {
            throw new RuntimeException("同一位置已绑定相同的设备");
        }
        //4.注册设备到IOT
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        //秘钥
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);

        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("注册设备失败");
        }
        //5.本地保存设备
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //查询设备影子
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new RuntimeException("查询设备影子失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }
        // 获取上报数据的reported
        DeviceShadowProperties reported = shadow.get(0).getReported();
        // 把数据转换为JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Map<String, Object>> list = new ArrayList<>();
        // 事件上报时间
        String eventTimeStr = reported.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        //封装数据
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.查询本地数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new RuntimeException("设备不存在");
        }
        //2.查询IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("查询设备详情失败");
        }
        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        //日期转换
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            deviceVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));
        }
        return deviceVo;
    }

    @Override
    public void updateDevice(Device device) {
        //判断同一位置是否绑定相同的设备
        Long count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, device.getProductKey())
                .eq(Device::getBindingLocation, device.getBindingLocation())
                .eq(Device::getLocationType, device.getLocationType())
                .eq(device.getPhysicalLocationType() != null, Device::getPhysicalLocationType, device.getPhysicalLocationType())
                .ne(device.getId() != null, Device::getId, device.getId())
        );
        if (count > 0) {
            throw new RuntimeException("同一位置已绑定相同的设备");
        }
        //更新iot设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        request.setBody(body);
        try {
            client.updateDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("更新设备失败");
        }
        //更新数据库设备
        this.updateById(device);
    }

    @Override
    public void deleteDeviceById(String iotId) {
        if (ObjectUtil.isEmpty(iotId)) {
            return;
        }
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("删除设备失败");
        }
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if(StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云IOT平台接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
